<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="铭牌编码" prop="templateCode">
        <el-input v-model="queryParams.templateCode" placeholder="请输入铭牌编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="铭牌名称" prop="templateName">
        <el-input v-model="queryParams.templateName" placeholder="请输入铭牌名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['data:nameplate:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['data:nameplate:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column label="铭牌编码" align="center" prop="templateCode">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{ scope.row.templateCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="铭牌名称" align="center" prop="templateName" />
      <el-table-column label="铭牌标题" align="center" prop="templateTitle" />
      <el-table-column label="是否启用" align="center" key="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bom_yes_no" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['data:nameplate:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['data:nameplate:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改铭牌模板表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="铭牌编码" prop="templateCode">
          <el-input v-model="form.templateCode" placeholder="请输入铭牌编码" />
        </el-form-item>
        <el-form-item label="铭牌名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入铭牌名称" />
        </el-form-item>
        <el-form-item label="铭牌标题" prop="templateTitle">
          <el-input v-model="form.templateTitle" placeholder="请输入铭牌标题" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>-->
      </el-form>

      <el-row :gutter="24" class="mb8">
        <el-col :span="12">
          <div class="addIcon">
            <el-button type="primary" icon="el-icon-plus" @click="leftAdd('0')"></el-button>
          </div>
          <div>
            <div class="inputDiv" v-for="(item, i) in leftList" :key="item.statsCode">
              <el-input v-model="item.statsName" :key="item.statsCode" placeholder="请输入" style="width: 200px;" />
              <!-- <i class="el-icon-edit"></i> -->
              <i class="el-icon-delete" @click="inputDel('0', i, item)"></i>
              <i v-if="i != 0" class="el-icon-top" @click="editSequence('0', i, '1')"></i>
              <i v-if="i != leftList.length - 1" class="el-icon-bottom" @click="editSequence('0', i, '2')"></i>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="addIcon">
            <el-button type="primary" icon="el-icon-plus" @click="leftAdd('1')"></el-button>
          </div>
          <div>
            <div class="inputDiv" v-for="(item, i) in rightList" :key="item.statsCode">
              <el-input v-model="item.statsName" :key="item.statsCode" placeholder="请输入" style="width: 200px;" />
              <!-- <i class="el-icon-edit"></i> -->
              <i class="el-icon-delete" @click="inputDel('1', i, item)"></i>
              <i v-if="i != 0" class="el-icon-top" @click="editSequence('1', i, '1')"></i>
              <i v-if="i != rightList.length - 1" class="el-icon-bottom" @click="editSequence('1', i, '2')"></i>
            </div>
          </div>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看铭牌 -->
    <el-dialog title="铭牌模板" :visible.sync="detailOpen" width="55%" append-to-body>
      <div class="templateDiv">
        <h3>{{ form.templateTitle }}</h3>
        <div class="temTitle">
          <div>
            <div class="rowDiv" v-for="(item) in leftList" :key="item.statsCode">
              <span>{{ item.statsName }}：</span>
              <span class="line"></span>
            </div>
          </div>
          <div>
            <div class="rowDiv" v-for="(item) in rightList" :key="item.statsCode">
              <span>{{ item.statsName }}：</span>
              <span class="line"></span>
            </div>
          </div>
        </div>
      </div>

      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>-->
    </el-dialog>
  </div>
</template>

<script>
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
  delTemplateStats
} from "@/api/mes/pro/protemplate";
import { v4 as uuidv4 } from "uuid";
export default {
  name: "Protemplate",
  dicts: ["bom_yes_no"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 铭牌模板表表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 铭牌弹层
      type: "",
      // 查看铭牌
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateCode: null,
        templateName: null,
        templateTitle: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        templateTitle: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      },
      leftList: [], //左侧列表
      rightList: [] //右侧列表
    };
  },
  created() {
    this.getList();
    console.log(uuidv4(), "====uuid=====");
  },
  methods: {
    /** 查询铭牌模板表列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateCode: null,
        templateName: null,
        templateTitle: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.leftList = [];
      this.rightList = [];
      this.type = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId);
      this.queryParams.proTemplateIdList = selection.map(item => item.templateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加铭牌模板表";
      this.type = "add";
      this.leftList = [
        {
          sequence: "0", //左  1  右
          orderNum: 1,
          statsName: undefined,
          statsCode: uuidv4(),
          status: "0",
          statsId: null
        }
      ]; //左侧列表
      this.rightList = [
        {
          sequence: "1", //左  1  右
          orderNum: 1,
          statsName: undefined,
          statsCode: uuidv4(),
          status: "0",
          statsId: null
        }
      ]; //右侧列表
    },
    // 查看按钮操作
    handleView(row) {
      this.reset();
      let templateId = row.templateId;

      getTemplate(templateId).then(response => {
        const { data, proTemplateStatsList } = response;
        this.form = {
          ...data
        };
        if (proTemplateStatsList && proTemplateStatsList.length > 0) {
          this.leftList = proTemplateStatsList.filter((item, index) => {
            return item.sequence == "0";
          });
          this.rightList = proTemplateStatsList.filter((item, index) => {
            return item.sequence == "1";
          });
        } else {
        }
        this.detailOpen = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids;
      this.open = true;
      this.type = "edit";
      getTemplate(templateId).then(response => {
        const { data, proTemplateStatsList } = response;
        this.form = {
          ...data
        };
        if (proTemplateStatsList && proTemplateStatsList.length > 0) {
          this.leftList = proTemplateStatsList.filter((item, index) => {
            return item.sequence == "0";
          });
          this.rightList = proTemplateStatsList.filter((item, index) => {
            return item.sequence == "1";
          });

          this.leftList.sort(this.sortBy("orderNum", 1));
          this.rightList.sort(this.sortBy("orderNum", 1));
          console.log(this.rightList, "=====this.rightList======");
          debugger;
        } else {
          this.leftList = [
            {
              sequence: "0", //左  1  右
              orderNum: 1,
              statsName: undefined,
              statsCode: uuidv4(),
              status: "0",
              statsId: null
            }
          ]; //左侧列表
          this.rightList = [
            {
              sequence: "1", //左  1  右
              orderNum: 1,
              statsName: undefined,
              statsCode: uuidv4(),
              status: "0",
              statsId: null
            }
          ]; //右侧列表
        }
        this.open = true;
        this.title = "修改铭牌模板表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = {};
          params = { ...this.form };
          params.proTemplateStatsList = [];
          let arry = [...this.leftList, ...this.rightList];
          // let arryNew = []
          arry.map((item, index) => {
            params.proTemplateStatsList.push(
              Object.assign({}, item, { templateId: this.form.templateId })
            );
          });
          if (this.form.templateId != null) {
            updateTemplate(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(params, "======params======");
            addTemplate(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 左右数组排序 //attr：根据该属性排序；rev：升序1或降序-1，不填则默认为1
    sortBy(attr, rev) {
      if (rev == undefined) {
        rev = 1;
      } else {
        rev ? 1 : -1;
      }
      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal
        .confirm('是否确认删除铭牌模板表编号为"' + templateIds + '"的数据项？')
        .then(function () {
          return delTemplate(templateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/mobile/pro/template/export",
        {
          ...this.queryParams
        },
        `template_${new Date().getTime()}.xlsx`
      );
    },
    // 铭牌增加
    leftAdd(type) {
      if (type === "0") {
        let index = this.leftList.length + 1;
        let addobj = {
          sequence: type, //左  1  右
          orderNum: index,
          statsName: undefined,
          statsCode: uuidv4(),
          status: "0",
          statsId: null
        };
        this.$nextTick(() => {
          this.leftList.push(addobj);
          console.log(this.leftList, "===========left=====");
        });
      } else {
        let index = this.rightList.length + 1;
        let addobj = {
          sequence: type, //左  1  右
          orderNum: index,
          statsName: undefined,
          statsCode: uuidv4(),
          status: "0",
          statsId: null
        };
        this.$nextTick(() => {
          this.rightList.push(addobj);
          console.log(this.rightList, "===========rightList=====");
        });
      }
    },
    // 删除
    inputDel(type, index, item) {
      const statsIds = item.statsId;
      if (!!statsIds) {
        this.$modal
          .confirm(
            '是否确认删除铭牌模板参数表编号为"' + statsIds + '"的数据项？'
          )
          .then(function () {
            return delTemplateStats(statsIds);
          })
          .then(() => {
            if (type == "0") {
              this.leftList.splice(index, 1);
            } else {
              this.rightList.splice(index, 1);
            }
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => { });
      } else {
        if (type == "0") {
          this.leftList.splice(index, 1);
        } else {
          this.rightList.splice(index, 1);
        }
      }
    },
    // 上移下移
    editSequence(type, index, topType) {
      //   1 上  2 下
      // 左边
      if (type == "0") {
        return topType === "1"
          ? this.upGo(this.leftList, index)
          : this.downGo(this.leftList, index);
      } else {
        // 右边
        return topType === "1"
          ? this.upGo(this.rightList, index)
          : this.downGo(this.rightList, index);
      }
    },
    // 向上移动
    upGo(fieldData, index) {
      if (index != 0) {
        fieldData[index].orderNum = index;
        fieldData[index - 1].orderNum = index + 1;
        fieldData[index] = fieldData.splice(index - 1, 1, fieldData[index])[0];
        console.log(fieldData, "======sort======");
      } else {
        fieldData.push(fieldData.shift());
      }
    },

    // 向下移动
    downGo(fieldData, index) {
      if (index != fieldData.length - 1) {
        fieldData[index].orderNum = index + 2;
        fieldData[index + 1].orderNum = index + 1;
        fieldData[index] = fieldData.splice(index + 1, 1, fieldData[index])[0];
        console.log(fieldData, "======sort======");
      } else {
        fieldData.unshift(fieldData.splice(index, 1)[0]);
      }
    }
  }
};
</script>
<style scoped>
.addIcon {
  text-align: center;
}

.inputDiv {
  margin-top: 20px;
  margin-left: 10px;
  display: flex;
  /* justify-content: center; */
  align-items: center;
}

.inputDiv i {
  font-size: 24px;
  margin: 0 10px;
}

.templateDiv {
  text-align: center;
  padding: 15px;
  padding-top: 0px;
  /* box-shadow: 3px 3px 3px 3px #eee; */
  border: 1px solid #aaa;
}

.templateDiv h3 {
  font-size: 20px;
  line-height: 40px;
  font-weight: 600;
}

.rowDiv {
  display: flex;
  align-items: flex-end;
  margin: 0 10px;
  margin-bottom: 25px;
  font-size: 16px;
}

.temTitle {
  display: flex;
  justify-content: center;
  /* justify-content: space-between; */
}

.temTitle>div {
  flex: 1;
}

.temTitle>div .rowDiv span:nth-child(1) {
  display: inline-block;
  min-width: 160px;
  height: 20px;
  text-align: right;
  /* white-space: nowrap; */
  text-align: justify;
}

.temTitle>div .rowDiv span:nth-child(1)::after {
  content: "";
  display: inline-block;
  width: 100%;
}

.temTitle>div {
  margin-left: 15px;
}

/* .rowDiv span:nth-child(1){
  line-height: 36px;
} */
.line {
  /* margin-left: 10px; */
  display: block;
  height: 2px;
  width: 50%;
  background-color: #999;
}
</style>
